package puziran.sofa.util;

import java.lang.reflect.InvocationTargetException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.PropertyUtils;

public class ParseFormToBean {
	public Object parseToBean(Map map, Object bean) {
		Iterator it = map.keySet().iterator();

		while (it.hasNext()) {
			Object keyName = it.next();
			if (!keyName.equals("EncodingFilter.FILTERED")) {
				String keyNameStr = keyName.toString();
				try {
					Class cls = PropertyUtils.getPropertyType(bean, keyNameStr);

					if (cls == null) {
						continue;
					}
					if (map.get(keyName) != null) {
						Object keyValue = ConvertUtils.convert(map.get(keyName)
								.toString(), cls);

						PropertyUtils.setProperty(bean, keyNameStr, keyValue);
					}
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				} catch (NoSuchMethodException e) {
					e.printStackTrace();
				}
			}
		}
		return bean;
	}

	public Object parseToBeanRemoveNum(Map map, Object bean) {
		Iterator it = map.keySet().iterator();

		while (it.hasNext()) {
			Object keyName = it.next();
			if (!keyName.equals("EncodingFilter.FILTERED")) {
				String keyNameStr = keyName.toString().substring(0,
						keyName.toString().length() - 1);
				try {
					Class cls = PropertyUtils.getPropertyType(bean, keyNameStr);
					if (cls == null)
						continue;
					Object keyValue = ConvertUtils.convert(map.get(keyName)
							.toString(), cls);

					PropertyUtils.setProperty(bean, keyNameStr, keyValue);
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				} catch (NoSuchMethodException e) {
					e.printStackTrace();
				}
			}
		}
		return bean;
	}
}